import gettext
import os
from PySide6.QtCore import QObject, Signal
from src.config import app_config


class Translator(QObject):
    language_changed = Signal()

    def __init__(self):
        super().__init__()
        self.translator = None
        self.current_lang = None
        self.localedir = os.path.join(os.path.dirname(os.path.dirname(
            os.path.dirname(os.path.abspath(__file__)))), 'locales')
        app_config.changed.connect(self.on_config_changed)

    def on_config_changed(self, key, value):
        if key == 'ui.language':
            self.load_language(value)

    def load_language(self, lang):
        if lang == self.current_lang and self.translator is not None:
            return

        self.current_lang = lang
        try:
            # gettext on some systems might not automatically handle 'zh-CN' to 'zh_CN' mapping.
            # We can provide fallbacks or normalize the language code.
            lang_codes = [lang]
            if '-' in lang:
                lang_codes.append(lang.replace('-', '_'))

            self.translator = gettext.translation(
                'messages', localedir=self.localedir, languages=lang_codes, fallback=True)
        except FileNotFoundError:
            # Fallback to NullTranslations if the .mo file is not found
            self.translator = gettext.NullTranslations()

        self.language_changed.emit()

    def get_translation(self, message):
        if self.translator:
            return self.translator.gettext(message)
        return message


# --- Singleton Instance ---
translator = Translator()


def _(message):
    """Translate a message using the singleton translator."""
    return translator.get_translation(message)
